package yxk.report.hr.hspm;

import com.google.common.collect.Maps;
import kd.bos.bill.OperationStatus;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.Tuple;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.dataentity.serialization.SerializationUtils;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.*;
import kd.bos.form.control.Control;
import kd.bos.form.control.Label;
import kd.bos.form.control.events.ProgressEvent;
import kd.bos.form.events.*;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.metadata.form.Style;
import kd.bos.metadata.form.container.FlexPanelAp;
import kd.bos.metadata.form.container.TabAp;
import kd.bos.metadata.form.control.LabelAp;
import kd.bos.metadata.form.control.VectorAp;
import kd.bos.mvc.form.FormView;
import kd.bos.orm.query.QFilter;
import kd.bos.orm.util.CollectionUtils;
import kd.bos.service.operation.OperationServiceImpl;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;
import kd.hr.hbp.business.servicehelper.HRMServiceHelper;
import kd.hr.hbp.common.control.HRFlexPanelAp;
import kd.hr.hbp.common.control.HRLabelAp;
import kd.hr.hbp.common.control.HRVectorAp;
import kd.hr.hbp.common.util.HRBaseUtils;
import kd.hr.hbp.common.util.HRJSONUtils;
import kd.hr.hbp.common.util.HRStringUtils;
import kd.hr.hpfs.business.service.ocr.HROcrValidateServiceHelper;
import kd.hr.hspm.business.helper.FileHeadHelper;
import kd.hr.hspm.business.mservice.IHspmOcrService;
import kd.hr.hspm.business.mservice.impl.HspmOcrServiceImpl;
import kd.hr.hspm.business.util.HpfsParamUtil;
import kd.hr.hspm.common.entity.ocr.AlgoResultData;
import kd.hr.hspm.formplugin.web.mobile.MobileHomeTemplatePlugin;
import kd.sdk.hr.hspm.business.helper.ApprovalHelper;
import kd.sdk.hr.hspm.business.repository.ErmanFileRepository;
import kd.sdk.hr.hspm.business.service.AttacheHandlerService;
import kd.sdk.hr.hspm.business.service.MultiViewTemplateService;
import kd.sdk.hr.hspm.business.service.PageRegConfigService;
import kd.sdk.hr.hspm.common.enums.ClientTypeEnum;
import kd.sdk.hr.hspm.common.ext.file.MobileHomeVectorDTO;
import kd.sdk.hr.hspm.common.model.FileRelationModel;
import kd.sdk.hr.hspm.common.utils.ApprovalEntityUtils;
import kd.sdk.hr.hspm.common.utils.BusinessUtils;
import kd.sdk.hr.hspm.common.utils.CommonUtil;
import kd.sdk.hr.hspm.common.utils.PageCacheUtils;
import kd.sdk.hr.hspm.formplugin.web.file.ermanfile.ext.service.employee.MobileHomeExtUtil;

import java.text.MessageFormat;
import java.util.*;
import java.util.stream.Collectors;

public class MobileHomePersonPlugin extends MobileHomeTemplatePlugin {
    private static final Log logger = LogFactory.getLog(MobileHomePersonPlugin.class);

    public MobileHomePersonPlugin() {
    }

    public void preOpenForm(PreOpenFormEventArgs e) {
        super.preOpenForm(e);
        if (this.isOldHss(e.getFormShowParameter())) {
            e.getFormShowParameter().setHasRight(true);
        }

        e.getFormShowParameter().setCustomParam("checkRightAppId", "hssc");
    }

    public void beforeBindData(EventObject args) {
        String isNotSigned = this.getPageCache().get("isNotSigned");
        logger.info("=============getcnfid:{}", this.getView().getPageCache().get("personId"));
        if (HRStringUtils.isNotEmpty(isNotSigned)) {
            this.showMenu(false);
        } else {
            this.showMenu(true);
            this.getView().setVisible(false, new String[]{"mtoolbarap"});
            long cnfId = 0L;
            FormShowParameter formShowParameter = this.getView().getFormShowParameter();
            String previewCnfId = (String)formShowParameter.getCustomParam("cnfId");
            logger.info("previewCnfId----previewCnfId:{}",previewCnfId);
            logger.info("personId----personId0:{}",this.getView().getPageCache().get("personId"));
            String isPreview = null;
            if (HRStringUtils.isNotEmpty(previewCnfId)) {
                this.getPageCache().put("ispreview", "1");
                cnfId = Long.parseLong(previewCnfId);
                isPreview = "1";
            } else {
                Tuple<Boolean, Long> cnfInfo = this.getConfigInfo();
                    if (!(Boolean) cnfInfo.item1) {
                        this.getView().setVisible(Boolean.FALSE, new String[]{"contentflex"});
                        return;
                    }

                    cnfId = (Long) cnfInfo.item2;

            }

            if (cnfId != 0L) {
                Map<String, Object> infoGroupConfig = PageRegConfigService.getInstance().getInfoGroupConfig(cnfId, ClientTypeEnum.EMPLOYEE_MOBILE.getCode(), isPreview);
                logger.info("getcnfid:{}", cnfId);
                logger.info("getinfoGroupConfig:{}", infoGroupConfig);
                if (infoGroupConfig != null && infoGroupConfig.size() != 0) {
                    List<Map<String, Object>> groups = (List)infoGroupConfig.get("mainentry");

                    Map<String, String> flexMap = Maps.newHashMapWithExpectedSize(20);
                    Iterator var11 = groups.iterator();

                    String personId;
                    while(var11.hasNext()) {
                        Map<String, Object> group = (Map)var11.next();
                        personId = (String)group.get("targetkey");
                        String pageNumber = (String)group.get("pagenumber");
                        flexMap.put(personId, pageNumber);
                    }
                    IPageCache pageCache = this.getView().getPageCache();
                    logger.info("flexMap:{}", flexMap);
                    pageCache.put("flexMap", SerializationUtils.toJsonString(flexMap));
                    pageCache.put("cnfjson", SerializationUtils.toJsonString(infoGroupConfig));
                    this.getView().setVisible(Boolean.FALSE, new String[]{"errorflex"});
                    ApprovalEntityUtils.initCacheFromEntry(this.getView(), infoGroupConfig);
                    FlexPanelAp flexPanelAp = this.createMainPanelAp();
                    personId = this.getView().getPageCache().get("personId");
                    logger.info("personId:{}", personId);
                    MultiViewTemplateService.getInstance().setApToView(flexPanelAp, "flexpanelapdyn", this.getView());
                    if (!HRStringUtils.isEmpty(personId)) {
                        this.setHeadValue(infoGroupConfig);
                        if (CommonUtil.existAuditingEntry(this.getView())) {
                            this.getView().setEnable(Boolean.FALSE, new String[]{"headsculpture"});
                        }

                        ApprovalHelper.handleSubmitButtonVisible(this.getView());
                    }
                } else {
                    this.getView().setVisible(Boolean.FALSE, new String[]{"contentflex"});
                }
            }
        }
    }

    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        this.initVisibleNotPassLabel();
    }

    private void initVisibleNotPassLabel() {
        String cnfStr = this.getView().getPageCache().get("cnfjson");
        logger.info("cnfStr----cnfStr:{}",cnfStr);
        if (!HRStringUtils.isEmpty(cnfStr)) {
            Map<String, Object> infoGroupConfig = (Map)SerializationUtils.fromJsonString(cnfStr, Map.class);
            List<Map<String, Object>> tabEntryList = (List)infoGroupConfig.get("mainentry");
            logger.info("tabEntryList----tabEntryList:{}",tabEntryList);
            Iterator var4 = tabEntryList.iterator();

            while(var4.hasNext()) {
                Map<String, Object> map = (Map)var4.next();
                String targetKey = String.valueOf(map.get("targetkey"));
                String groupName = String.valueOf(map.get("groupname"));
                if (ApprovalHelper.isNotPasss(this.getView(), targetKey, groupName)) {
                    this.getView().setVisible(true, new String[]{targetKey.toLowerCase(Locale.ROOT) + "notpass"});
                } else {
                    this.getView().setVisible(false, new String[]{targetKey.toLowerCase(Locale.ROOT) + "notpass"});
                }
            }

        }
    }

    private void showMenu(boolean isVisible) {
        if (this.getView() instanceof IMobileView) {
            ((IMobileView)this.getView()).setMenuItemVisible(isVisible, new String[]{"auditrecord"});
        }

    }

    public void propertyChanged(PropertyChangedArgs e) {
        String headsculpturesuccess = this.getPageCache().get("headsculpture");
        if (headsculpturesuccess != null && !Boolean.parseBoolean(headsculpturesuccess)) {
            this.getPageCache().remove("headsculpture");
        } else {
            String name = e.getProperty().getName();
            if (e.getChangeSet()[0].getNewValue() != null) {
                String newValue = e.getChangeSet()[0].getNewValue() + "";
                if ("headsculpture".equals(name)) {
                    String imageFullUrl = HspmOcrServiceImpl.getImageFullUrl(newValue + "");
                    logger.info("headocr=={}===={}==={}", new Object[]{HROcrValidateServiceHelper.checkOcrLicenseGroup(), newValue, imageFullUrl});
                    String errMsg = ResManager.loadKDString("人脸识别失败，无法修改头像！", "HeadDrawPlugin_0", "hr-hspm-formplugin", new Object[0]);

                    try {
                        if (HpfsParamUtil.isOpenOcr() && HROcrValidateServiceHelper.checkOcrLicenseGroup()) {
                            this.getView().showLoading(new LocaleString(ResManager.loadKDString("OCR人脸识别中，请稍候...", "HeadDrawPlugin_6", "hr-hspm-formplugin", new Object[0])));
                            AlgoResultData data = IHspmOcrService.getInstance().detectFaceImage(newValue);
                            logger.info("PersonInfoEditPlugin#beforeDoOperation algoResultData: {}", data);
                            if (data == null || data.getErrorCode() != 0 || data.getData() == null) {
                                this.getView().showTipNotification(ResManager.loadKDString("人脸识别失败，无法修改头像！", "HeadDrawPlugin_0", "hr-hspm-formplugin", new Object[0]));
                                this.getPageCache().put("headsculpture", "false");
                                this.getModel().beginInit();
                                this.getModel().setValue("headsculpture", e.getChangeSet()[0].getOldValue());
                                this.getModel().endInit();
                                return;
                            }

                            if (!"1".equals(((Map)data.getData()).get("face_number").toString())) {
                                this.getView().showTipNotification(ResManager.loadKDString("图片必须包含单个人像！", "HeadDrawPlugin_1", "hr-hspm-formplugin", new Object[0]));
                                this.getPageCache().put("headsculpture", "false");
                                this.getModel().beginInit();
                                this.getModel().setValue("headsculpture", e.getChangeSet()[0].getOldValue());
                                this.getModel().endInit();
                                return;
                            }
                        }

                        String personId = this.getView().getPageCache().get("personId");
                        if (this.isHeadNeedAuditOrIsEdit("isaudit")) {
                            String entrycache = PageCacheUtils.getHomePageCache(this.getView()).get("0000-entrycache");
                            List<HashMap<String, Object>> collection = new ArrayList();
                            if (HRStringUtils.isNotEmpty(entrycache)) {
                                collection = (List)SerializationUtils.fromJsonString(entrycache, List.class);
                            }

                            BusinessUtils.addMapToCollect(this.getView(), Long.valueOf(personId), "headsculpture", newValue, this.getView().getPageCache().get("oldheadpic"), (List)collection, "hrpi_person");
                            this.getView().showTipNotification(ResManager.loadKDString("修改后的头像需提交审核方可生效", "MobileHomeTemplatePlugin_9", "hr-hspm-formplugin", new Object[0]));
                        } else {
                            AttacheHandlerService.getInstance().saveHeadsCulpture(personId, newValue);
                        }
                    } catch (Exception var13) {
                        logger.error(errMsg, var13);
                        this.getView().showErrorNotification(errMsg);
                        this.getPageCache().put("headsculpture", String.valueOf(true));
                        this.getModel().beginInit();
                        this.getModel().setValue("headsculpture", e.getChangeSet()[0].getOldValue());
                        this.getModel().endInit();
                        return;
                    } finally {
                        this.getView().hideLoading();
                    }

                    this.getPageCache().remove("headsculpture");
                }

            }
        }
    }

    private boolean isHeadNeedAuditOrIsEdit(String field) {
        String cnfStr = this.getView().getPageCache().get("cnfjson");
        Map<String, Object> infoGroupConfig = (Map)SerializationUtils.fromJsonString(cnfStr, Map.class);
        List<Map<String, Object>> headEntity = (List)infoGroupConfig.get("headentity");
        long count = headEntity.stream().filter((map) -> {
            return map.get("number").equals("headsculpture") && Boolean.TRUE.equals(map.get(field));
        }).count();
        return count > 0L;
    }

    private void setHeadValue(Map<String, Object> infoGroupConfig) {
        List<Map<String, Object>> headEntity = (List)infoGroupConfig.get("headentity");
        logger.info("headEntity:{}", headEntity);
        FormShowParameter formShowParameter = this.getView().getFormShowParameter();
        String personId = this.getView().getPageCache().get("personId");
        if (!HRStringUtils.isEmpty(personId)) {
            DynamicObject erFileDy = ErmanFileRepository.getPrimaryErmanFile(Long.parseLong(personId));
            this.setCustomParams(formShowParameter, erFileDy);
            Map<String, Object> typeMap = new HashMap(2);
            typeMap.put("number", "apositiontype");
            typeMap.put("source", "hrpi_empposorgrel");
            headEntity.add(typeMap);
            Map<String, DynamicObject> stringDynamicObjectMap = FileHeadHelper.queryDataFromDb(headEntity, formShowParameter);
            headEntity.remove(typeMap);
            if (stringDynamicObjectMap.size() > 0) {
                DynamicObject empPosDy = (DynamicObject)stringDynamicObjectMap.get("hrpi_empposorgrel");
                DynamicObject personDy = (DynamicObject)stringDynamicObjectMap.get("hrpi_person");
                String entrycache;
                if (personDy != null) {
                    String nameNumber = "";
                    if (HRStringUtils.isNotEmpty(personDy.getString("name"))) {
                        nameNumber = nameNumber + personDy.getString("name");
                    }

                    if (HRStringUtils.isNotEmpty(personDy.getString("number"))) {
                        if (nameNumber.length() > 0) {
                            nameNumber = nameNumber + "  " + personDy.getString("number");
                        } else {
                            nameNumber = nameNumber + personDy.getString("number");
                        }
                    }

                    if (HRStringUtils.isNotEmpty(nameNumber)) {
                        this.setLabelText("username", nameNumber);
                    } else {
                        this.getView().setVisible(Boolean.FALSE, new String[]{"usernameflex"});
                    }

                    this.getView().getPageCache().put("oldheadpic", personDy.getString("headsculpture"));
                    if (!this.isHeadNeedAuditOrIsEdit("isedit")) {
                        this.getView().setEnable(Boolean.FALSE, new String[]{"headsculpture"});
                    }

                    this.getModel().beginInit();
                    this.getModel().setValue("headsculpture", personDy.getString("headsculpture"));
                    this.getView().updateView("headsculpture");
                    this.getModel().endInit();
                    if (this.isHeadNeedAuditOrIsEdit("isaudit")) {
                        entrycache = PageCacheUtils.getHomePageCache(this.getView()).get("0000-entrycache");
                        List<HashMap<String, Object>> collection = new ArrayList();
                        if (HRStringUtils.isNotEmpty(entrycache)) {
                            collection = (List)SerializationUtils.fromJsonString(entrycache, List.class);
                        }

                        Optional<HashMap<String, Object>> first = collection.stream().filter((map) -> {
                            return map.get("dataid").toString().equals(personId) && map.get("fieldname").equals("headsculpture") && map.get("entityName").equals("hrpi_person");
                        }).findFirst();
                        if (first.isPresent()) {
                            String newValue = (String)((HashMap)first.get()).get("newvalue");
                            if (!HRStringUtils.isEmpty(newValue)) {
                                this.getModel().beginInit();
                                this.getModel().setValue("headsculpture", newValue);
                                this.getModel().endInit();
                            }
                        }
                    }
                }

                List<Object> headFields = (List)headEntity.stream().map((field) -> {
                    return field.get("number");
                }).collect(Collectors.toList());
                if (empPosDy != null) {
                    this.handlePositionLine(headFields, empPosDy);
                    entrycache = null;
                    if (headFields.contains("company") && empPosDy.get("company") != null) {
                        entrycache = empPosDy.getDynamicObject("company").getString("name");
                    }

                    this.setLabelText("company", entrycache);
                }

                this.handleDepName(headFields);
            }

        }
    }

    private void handleDepName(List<Object> headFields) {
        String depname = null;
        if (headFields.contains("depname")) {
            Long fileId = HRJSONUtils.getLongValOfCustomParam(this.getView().getFormShowParameter().getCustomParam("erfileid"));
            FileRelationModel fileRelationModel = FileHeadHelper.getFileRelationInfo(fileId);
            List<Map<String, Object>> depChargeInfoList = fileRelationModel.getDepChargeInfoList();
            if (depChargeInfoList != null && depChargeInfoList.size() > 0) {
                Map<String, Object> depMap = (Map)depChargeInfoList.get(0);
                if (depMap != null) {
                    depname = (String)depMap.get("name");
                }
            }
        }

        if (HRStringUtils.isNotEmpty(depname)) {
            StringBuilder sb = new StringBuilder(ResManager.loadKDString("部门负责人", "MobileHomeTemplatePlugin_12", "hr-hspm-formplugin", new Object[0]));
            sb.append("： ");
            sb.append(depname);
            depname = sb.toString();
        }

        this.setLabelText("depname", depname);
    }

    private void handlePositionLine(List<Object> headFields, DynamicObject empPosDy) {
        DynamicObject dynamicObject = null;
        String apositonType = empPosDy.getString("apositiontype");
        if ("0".equals(apositonType)) {
            if (headFields.contains("stdposition")) {
                dynamicObject = empPosDy.getDynamicObject("stdposition");
            }
        } else if ("1".equals(apositonType)) {
            if (headFields.contains("position")) {
                dynamicObject = empPosDy.getDynamicObject("position");
            }
        } else if ("2".equals(apositonType) && headFields.contains("job")) {
            dynamicObject = empPosDy.getDynamicObject("job");
        }

        String value = dynamicObject != null && HRStringUtils.isNotEmpty(dynamicObject.getString("name")) ? dynamicObject.getString("name") : "";
        if (headFields.contains("adminorg") && empPosDy.getDynamicObject("adminorg") != null) {
            DynamicObject adminorg = empPosDy.getDynamicObject("adminorg");
            if (HRStringUtils.isNotEmpty(adminorg.getString("name"))) {
                if (HRStringUtils.isNotEmpty(value)) {
                    value = value + " | " + adminorg.getString("name");
                } else {
                    value = adminorg.getString("name");
                }
            }
        }

        this.setLabelText("position", value);
    }

    private Tuple<Boolean, Long> getConfigInfo() {
        Long cnfId = 0L;
        Long person=0L;
        FormShowParameter formShowParameter = this.getView().getFormShowParameter();
        try {
              String manfilelist = formShowParameter.getCustomParam("userermanfilelist");
              if( manfilelist==null){
                  Map<String, Object> resultPerson = (Map) HRMServiceHelper.invokeHRMPService("hrpi", "IHRPIPersonService", "getPersonModelId", new Object[0]);
                  logger.info("getPersonModelIdResp{}", resultPerson);
                  if (resultPerson != null && resultPerson.size() != 0) {
                      Map<String, Object> idData = (Map) resultPerson.get("data");
                      logger.info("idData{}", idData);
                      person = (Long) idData.get("person");
                  }else{
                      this.getModel().setValue("errorinfo", ResManager.loadKDString("登录用户获取的人员信息为空", "MobileHomeTemplatePlugin_0", "hr-hspm-formplugin", new Object[0]));
                      return Tuple.create(Boolean.FALSE, cnfId);
                  }
              }else {
                  person = Long.parseLong(formShowParameter.getCustomParam("person").toString());
              }
             boolean reqPerson = false;
           // if (resultPerson != null && resultPerson.size() != 0) {
              /*  Map<String, Object> idData = (Map)resultPerson.get("data");
                logger.info("idData{}", idData);*/
                if (person != 0L) {
                    DynamicObject erFileDy = ErmanFileRepository.getPrimaryErmanFile(person);
                    IPageCache pageCache = this.getView().getPageCache();
                    String personId = String.valueOf(person);
                    logger.info("personId{}", personId);
                    pageCache.put("personId", personId);
                    if (erFileDy == null) {
                        this.getModel().setValue("errorinfo", ResManager.loadKDString("登录用户获取的人员档案为空", "MobileHomeTemplatePlugin_2", "hr-hspm-formplugin", new Object[0]));
                        return Tuple.create(Boolean.FALSE, cnfId);
                    } else {
                        Tuple<Boolean, Long> tuple = AttacheHandlerService.getInstance().handleRuleEngine(this.getView(), erFileDy.getLong("id"), erFileDy, "hspm" + ClientTypeEnum.EMPLOYEE_MOBILE.getCode(), ClientTypeEnum.EMPLOYEE_MOBILE.getCode(), (Map)null, false);
                        cnfId = (Long)tuple.item2;
                        Boolean getRule = (Boolean)tuple.item1;
                        if (!getRule) {
                            this.getView().showTipNotification(ResManager.loadKDString("没有匹配的业务规则，当前页面将为您显示默认方案。若不符合要求，请联系管理员调整业务规则", "MultiViewTemplatePlugin_1", "hr-hspm-formplugin", new Object[0]));
                        }

                        return Tuple.create(Boolean.TRUE, cnfId);
                    }
                } else {
                    this.getModel().setValue("errorinfo", ResManager.loadKDString("登录用户获取的人员ID为空", "MobileHomeTemplatePlugin_1", "hr-hspm-formplugin", new Object[0]));
                    return Tuple.create(Boolean.FALSE, cnfId);
                }
          /*  } else {
                this.getModel().setValue("errorinfo", ResManager.loadKDString("登录用户获取的人员信息为空", "MobileHomeTemplatePlugin_0", "hr-hspm-formplugin", new Object[0]));
                return Tuple.create(Boolean.FALSE, cnfId);
            }*/
        } catch (Exception var10) {
            this.getModel().setValue("errorinfo", ResManager.loadKDString("调用获取人员信息异常", "MobileHomeTemplatePlugin_3", "hr-hspm-formplugin", new Object[0]));
            logger.error("getPersonModelIdError", var10);
            return Tuple.create(Boolean.FALSE, cnfId);
        }
    }

    private void setLabelText(String key, String value) {
        Label label;
        if (HRStringUtils.isNotEmpty(value) && (label = (Label)this.getControl(key)) != null) {
            label.setText(value);
        } else {
            this.getView().setVisible(Boolean.FALSE, new String[]{key + "flex"});
        }

    }

    public FlexPanelAp createMainPanelAp() {
        String cnfStr = this.getView().getPageCache().get("cnfjson");
        Map<String, Object> infoGroupConfig = (Map)SerializationUtils.fromJsonString(cnfStr, Map.class);
        FlexPanelAp flexPanelAp = ((HRFlexPanelAp.Builder)(new HRFlexPanelAp.Builder("dynglobalpanel")).setWrap(false).setDirection("row").setGrow(1).setShrink(1).setAlignItems("stretch").setMarginBottom("10px")).setWidth("100%").build();
        flexPanelAp.getItems().add(this.buildPanelAp(infoGroupConfig));
        return flexPanelAp;
    }

    public FlexPanelAp buildPanelAp(Map<String, Object> infoGroupConfig) {
        TabAp tabAp = new TabAp();
        tabAp.setKey("tabap");
        tabAp.setId("tabap");
        tabAp.setName(new LocaleString("tabap"));
        List<Map<String, Object>> tabEntryList = (List)infoGroupConfig.get("mainentry");
        FlexPanelAp rightPanelAp = (new HRFlexPanelAp.Builder("dynglobalpanel")).build();
        rightPanelAp.getItems().add(this.buildAssociPanel(tabEntryList));
        return rightPanelAp;
    }

    public void onGetControl(OnGetControlArgs args) {
        FormView view = (FormView)this.getView();
        logger.info(MessageFormat.format("key:{0}", args.getKey()));
        MultiViewTemplateService.getInstance().setLabelClick(args, view, this, "mainentry");
        String key = args.getKey();
        Label relateLabel;
        if ("auditrecord".equals(key)) {
            relateLabel = new Label();
            relateLabel.setKey("auditRecord");
            relateLabel.setView(this.getView());
            relateLabel.addClickListener(this);
            args.setControl(relateLabel);
        } else if ("changeRecord".equalsIgnoreCase(key)) {
            relateLabel = new Label();
            relateLabel.setKey("changeRecord");
            relateLabel.setView(this.getView());
            relateLabel.addClickListener(this);
            args.setControl(relateLabel);
        }

        if (key.contains("lbl") || key.contains("vec")) {
            relateLabel = new Label();
            relateLabel.setKey(key);
            relateLabel.setView(this.getView());
            relateLabel.addClickListener(this);
            args.setControl(relateLabel);
        }

    }

    private FlexPanelAp buildAssociPanel(List<Map<String, Object>> mainEntryList) {
        FlexPanelAp relatePanel = (new HRFlexPanelAp.Builder("dynglobalpanel")).setForeColor("#333333").setGrow(0).setShrink(0).setWrap(false).setDirection("column").setJustifyContent("center").setWidth("100%").build();
        FlexPanelAp relatePageInfoPanelAp = this.createRelatePageInfoPanelAp(mainEntryList);
        relatePanel.getItems().add(relatePageInfoPanelAp);
        return relatePanel;
    }

    public FlexPanelAp createRelatePageInfoPanelAp(List<Map<String, Object>> mainEntryList) {
        FlexPanelAp relatePanelAp = (new HRFlexPanelAp.Builder("relatepageflexpanellistap")).setWrap(false).setDirection("column").setJustifyContent("center").setAlignItems("flex-start").setAlignContent("flex-start").setGrow(1).setWidth("100%").setShrink(0).build();
        FormShowParameter formShowParameter = this.getView().getFormShowParameter();
        String manfilelist = formShowParameter.getCustomParam("userermanfilelist");
        if( manfilelist == null) {
            this.addMenuGroup(mainEntryList);
        }

        if (mainEntryList != null && mainEntryList.size() != 0) {
            MobileHomeVectorDTO mobileHomeVectorDTO = new MobileHomeVectorDTO();
            MobileHomeExtUtil.modifyMobileHomeVector(mobileHomeVectorDTO);
            Iterator var4 = mainEntryList.iterator();

            while(var4.hasNext()) {
                Map<String, Object> manMap = (Map)var4.next();
                String pageKey = (String)manMap.get("targetkey");
                String groupName = (String)manMap.get("groupname");
                FlexPanelAp itemPanelAp = ((HRFlexPanelAp.Builder)((HRFlexPanelAp.Builder)(new HRFlexPanelAp.Builder(pageKey)).setWrap(false).setOverflow("visible").setDirection("row").setJustifyContent("space-between").setAlignItems("center").setGrow(1).setShrink(0).setBackColor("#ffffff").setClickable(true).setPaddingLeft("12px")).setMarginTop("12px")).setHeight("48px").setWidth("100%").build();
                FlexPanelAp leftFlex = (new HRFlexPanelAp.Builder(pageKey + "left")).setGrow(0).setShrink(0).setDirection("row").build();
                if (mobileHomeVectorDTO.getEnable()) {
                    this.MenuVectorEx(leftFlex, pageKey, mobileHomeVectorDTO);
                }

                LabelAp itemLabel = (new HRLabelAp.Builder(pageKey + "-lbl")).setId(pageKey + "-lbl").setName(groupName).setFontSize(16).setClickable(true).setTextAlign("flex-start").setGrow(0).setShrink(0).build();
                leftFlex.getItems().add(itemLabel);
                FlexPanelAp build = (new HRFlexPanelAp.Builder(pageKey + "right")).setGrow(0).setShrink(0).setDirection("row").build();
                if (!pageKey.equals("auditRecord") && !pageKey.equals("changeRecord")) {
                    LabelAp labelAp = new LabelAp();
                    labelAp.setKey(pageKey + "notpass");
                    labelAp.setName(new LocaleString(ResManager.loadKDString("不通过", "InfoGroupApprovalUtil_1", "sdk-hr", new Object[0])));
                    labelAp.setShrink(0);
                    labelAp.setGrow(0);
                    labelAp.setAlignSelf("center");
                    labelAp.setForeColor("#FB2323");
                    labelAp.setAutoTextWrap(false);
                    labelAp.setFontSize(14);
                    build.getItems().add(labelAp);
                }

                VectorAp entryVectorAp = ((HRVectorAp.Builder)(new HRVectorAp.Builder(pageKey + "-vec")).setfontClass("kdfont kdfont-houfan").setWidth(new LocaleString("16px")).setHeight(new LocaleString("16px")).setMarginRight("12px")).setAlignSelf("center").build();
                build.getItems().add(entryVectorAp);
                itemPanelAp.getItems().add(leftFlex);
                itemPanelAp.getItems().add(build);
                relatePanelAp.getItems().add(itemPanelAp);
            }

            return relatePanelAp;
        } else {
            return relatePanelAp;
        }
    }

    private void MenuVectorEx(FlexPanelAp leftFlex, String pageKey, MobileHomeVectorDTO mobileHomeVectorDTO) {
        Map<String, String> vectorMap = mobileHomeVectorDTO.getVectorMap();
        String vectorPath = null;
        if (!CollectionUtils.isEmpty(vectorMap)) {
            vectorPath = (String)vectorMap.get(pageKey);
        }

        VectorAp preVectorAp = ((HRVectorAp.Builder)(new HRVectorAp.Builder(pageKey + "-vector")).setfontClass(HRStringUtils.isNotEmpty(vectorPath) ? vectorPath : mobileHomeVectorDTO.getDefaultVetor()).setWidth(new LocaleString("16px")).setHeight(new LocaleString("16px")).setMarginRight("12px")).setAlignSelf("center").build();
        Map<String, Style> vectorStyleMap = mobileHomeVectorDTO.getVectorStyleMap();
        if (!CollectionUtils.isEmpty(vectorStyleMap)) {
            Style vectorStyle = (Style)vectorStyleMap.get(pageKey);
            if (vectorStyle != null) {
                preVectorAp.setStyle(vectorStyle);
            }
        }

        Map<String, Map<String, String>> colorAndSizeMap = mobileHomeVectorDTO.getColorAndSizeMap();
        if (!CollectionUtils.isEmpty(colorAndSizeMap)) {
            Map<String, String> colorAndSize = (Map)colorAndSizeMap.get(pageKey);
            if (colorAndSize != null && !colorAndSize.isEmpty()) {
                String forecolor = (String)colorAndSize.get("forecolor");
                if (HRStringUtils.isNotEmpty(forecolor)) {
                    preVectorAp.setForeColor(forecolor);
                }

                String backcolor = (String)colorAndSize.get("backcolor");
                if (HRStringUtils.isNotEmpty(backcolor)) {
                    preVectorAp.setBackColor(backcolor);
                }

                String width = (String)colorAndSize.get("width");
                if (HRStringUtils.isNotEmpty(width)) {
                    preVectorAp.setWidth(new LocaleString(width));
                }

                String height = (String)colorAndSize.get("height");
                if (HRStringUtils.isNotEmpty(height)) {
                    preVectorAp.setHeight(new LocaleString(height));
                }

                String fontclass = (String)colorAndSize.get("fontclass");
                if (HRStringUtils.isNotEmpty(fontclass)) {
                    preVectorAp.setfontClass(fontclass);
                }

                String fontsize = (String)colorAndSize.get("fontsize");
                if (HRStringUtils.isNotEmpty(fontsize)) {
                    preVectorAp.setFontSize(Integer.parseInt(fontsize));
                }

                String fontweight = (String)colorAndSize.get("fontweight");
                if (HRStringUtils.isNotEmpty(fontweight)) {
                    preVectorAp.setFontWeight(fontweight);
                }

                String radius = (String)colorAndSize.get("radius");
                if (HRStringUtils.isNotEmpty(radius)) {
                    preVectorAp.setRadius(radius);
                }

                String grow = (String)colorAndSize.get("grow");
                if (HRStringUtils.isNotEmpty(grow)) {
                    preVectorAp.setGrow(Integer.parseInt(grow));
                }

                String shrink = (String)colorAndSize.get("shrink");
                if (HRStringUtils.isNotEmpty(shrink)) {
                    preVectorAp.setShrink(Integer.parseInt(shrink));
                }

                String customestyles = (String)colorAndSize.get("customestyles");
                if (HRStringUtils.isNotEmpty(customestyles)) {
                    preVectorAp.setCustomeStyles(customestyles);
                }

                String alignself = (String)colorAndSize.get("alignself");
                if (HRStringUtils.isNotEmpty(alignself)) {
                    preVectorAp.setAlignSelf(alignself);
                }

                String zindex = (String)colorAndSize.get("zindex");
                if (HRStringUtils.isNotEmpty(zindex)) {
                    preVectorAp.setZIndex(Integer.parseInt(zindex));
                }
            }
        }

        leftFlex.getItems().add(preVectorAp);
    }

    private void addMenuGroup(List<Map<String, Object>> groups) {
        if (groups != null) {
            Map<String, Object> auditRecord = new HashMap(4);
            auditRecord.put("targetkey", "auditRecord");
            auditRecord.put("pagenumber", "auditRecord");
            auditRecord.put("groupname", ResManager.loadKDString("档案审批记录", "MobileHomeTemplatePlugin_10", "hr-hspm-formplugin", new Object[0]));
            groups.add(0, auditRecord);
            Map<String, Object> changeRecord = new HashMap(4);
            changeRecord.put("targetkey", "changeRecord");
            changeRecord.put("pagenumber", "changeRecord");
            changeRecord.put("groupname", ResManager.loadKDString("档案修改记录", "MobileHomeTemplatePlugin_11", "hr-hspm-formplugin", new Object[0]));
            groups.add(1, changeRecord);
        }

    }

    public void registerListener(EventObject eventObject) {
        this.addClickListeners(new String[]{"submit", "auditrecord", "changerecord", "close", "abandon"});
        ApprovalHelper.setSubmitButtonVisibleListener(this.getView(), this);
    }

    public void click(EventObject evt) {
        String key = ((Control)evt.getSource()).getKey();
        logger.info(MessageFormat.format("click key:{0}", key));
        if ("submit".equals(key)) {
            ApprovalHelper.submitConfirm(this.getView(), this);
        } else if (!key.equals("auditrecord-lbl") && !key.equals("auditrecord-vec") && !key.equals("auditRecord")) {
            if (!key.equals("changerecord-lbl") && !key.equals("changerecord-vec") && !key.equals("changeRecord")) {
                String flexMapStr;
                if (key.equals("close")) {
                    this.getView().setVisible(false, new String[]{"headtipspanel"});
                    this.getView().setVisible(false, new String[]{"notpassvector"});
                    this.getView().getPageCache().put("closeHeadTipsPanel", "true");
                } else if (key.equals("abandon")) {
                    flexMapStr = this.getModel().getChangeDesc();
                    this.getView().showConfirm(ResManager.loadKDString("操作放弃后，将恢复原始值，请确定是否继续？", "AbstractMobileFormDrawEdit_8", "hr-hspm-formplugin", new Object[0]), flexMapStr, MessageBoxOptions.OKCancel, ConfirmTypes.Save, new ConfirmCallBackListener("abandon", this));
                }

                if (!key.contains("lbl") && !key.contains("vec")) {
                    flexMapStr = this.getPageCache().get("flexMap");
                    if (HRStringUtils.isNotEmpty(flexMapStr)) {
                        Map<String, String> flexMap = (Map)SerializationUtils.fromJsonString(flexMapStr, Map.class);
                        if (!CollectionUtils.isEmpty(flexMap) && flexMap.containsKey(key)) {
                            this.showFilePage(key, ShowType.Floating, "");
                        }
                    }

                } else {
                    this.showFilePage(key.split("-")[0].toUpperCase(), ShowType.Floating, "");
                }
            } else {
                ApprovalHelper.viewChangeRecord(this.getView());
            }
        } else {
            ApprovalHelper.viewAuditRecord(this.getView());
        }
    }

    public void contextMenuClick(ContextMenuClickEvent evt) {
        super.contextMenuClick(evt);
        logger.info("contextMenuClick method");
        String isNotSigned = this.getPageCache().get("isNotSigned");
        if (HRStringUtils.isNotEmpty(isNotSigned)) {
            this.getView().showConfirm(ResManager.loadKDString("您未签署隐私，暂时不允许执行该操作", "MobileHomeTemplatePlugin_4", "hr-hspm-business", new Object[0]), MessageBoxOptions.None);
        } else {
            if (evt.getItemKey().equalsIgnoreCase("auditrecord")) {
                ApprovalHelper.viewAuditRecord(this.getView());
            } else if (evt.getItemKey().equalsIgnoreCase("changerecord")) {
                ApprovalHelper.viewChangeRecord(this.getView());
            }

        }
    }

    public void beforeClosed(BeforeClosedEvent closedEvent) {
        super.beforeClosed(closedEvent);
        logger.info("beforeClosed....");
        if (!"true".equals(this.getView().getPageCache().get("HomePageClose")) && ApprovalHelper.existAuditInfo(this.getView())) {
            ConfirmCallBackListener confirm = new ConfirmCallBackListener("HomePageCloseCallBack", this);
            String msg = ResManager.loadKDString("检测到您有未提交审核的更改内容，是否直接退出？若不提交审核，将丢失这些更改。", "MobileHomeTemplatePlugin_5", "hr-hspm-formplugin", new Object[0]);
            this.getView().showConfirm(msg, MessageBoxOptions.OKCancel, confirm);
            closedEvent.setCancel(true);
        }

    }

    public void confirmCallBack(MessageBoxClosedEvent messageBoxClosedEvent) {
        super.confirmCallBack(messageBoxClosedEvent);
        MessageBoxResult result = messageBoxClosedEvent.getResult();
        if (MessageBoxResult.Yes.equals(result) || MessageBoxResult.OK.equals(result)) {
            String key = messageBoxClosedEvent.getCallBackId();
            if ("ApprovalSubmitCallBack".equals(key)) {
                ApprovalHelper.submit(this.getView());
            } else if ("HomePageCloseCallBack".equals(key)) {
                logger.info("HomePageCloaseCallBack...");
                ApprovalHelper.delCacheData(this.getView());
                IFormView view = this.getView();
                view.getPageCache().put("HomePageClose", "true");
                if (this.getView().getParentView() != null) {
                    logger.info(MessageFormat.format("backtoparentview:[{0}]", this.getView().getParentView().getEntityId()));
                    view.sendFormAction(this.getView().getParentView());
                }

                view.close();
            } else if ("abandon".equals(key)) {
                PageCacheUtils.getHomePageCache(this.getView()).remove("0000-entrycache");
                this.deleteHeadData();
                this.getView().updateView();
                this.getView().setVisible(Boolean.FALSE, new String[]{"headtipspanel"});
                this.getView().setVisible(Boolean.FALSE, new String[]{"notpassvector"});
            }

        }
    }

    private void deleteHeadData() {
        String personId = this.getView().getPageCache().get("personId");
        if (!HRStringUtils.isEmpty(personId)) {
            DynamicObject[] currentEntry = CommonUtil.getCurrentEntry(Long.valueOf(personId));
            if (currentEntry != null && currentEntry.length != 0) {
                HRBaseServiceHelper serviceHelper = new HRBaseServiceHelper("hspm_infoapproval");
                DynamicObject dynamicObject = currentEntry[0];
                DynamicObjectCollection entryentity = dynamicObject.getDynamicObjectCollection("entryentity");
                Iterator<DynamicObject> iterator = entryentity.iterator();

                while(iterator.hasNext()) {
                    DynamicObject next = (DynamicObject)iterator.next();
                    if (next.get("firstgroupnum").equals("0000")) {
                        PageCacheUtils.getHomePageCache(this.getView()).remove("0000-entrycache");
                        iterator.remove();
                    }
                }

                serviceHelper.updateOne(dynamicObject);
                if (entryentity.size() == 0) {
                    OperationServiceImpl operationService = new OperationServiceImpl();
                    operationService.localInvokeOperation("unsubmit", new DynamicObject[]{dynamicObject}, OperateOption.create());
                    serviceHelper.deleteOne(dynamicObject.getPkValue());
                    PageCacheUtils.getHomePageCache(this.getView()).remove("submitVerson");
                }

            }
        }
    }

    private void showFilePage(String page, ShowType showType, String targetKey) {
        logger.info(MessageFormat.format("page:{0},showType:{1},targetKey:{2}", page, showType, targetKey));
        MobileFormShowParameter showParameter = new MobileFormShowParameter();
        showParameter.getOpenStyle().setShowType(showType);
        String formId = "";
        Map<String, String> flexMap = (Map)SerializationUtils.fromJsonString(this.getView().getPageCache().get("flexMap"), Map.class);
        if (flexMap != null && flexMap.containsKey(page)) {
            formId = (String)flexMap.get(page);
        }

        if (!this.isOldHss(this.getView().getFormShowParameter()) && !CommonUtil.hasPerm(formId, "47150e89000000ac", "hssc")) {
            this.getView().showErrorNotification(HRBaseUtils.getNoPermMsg());
        } else {
            if (showType.equals(ShowType.InContainer)) {
                showParameter.getOpenStyle().setTargetKey(targetKey);
                showParameter.setStatus(OperationStatus.VIEW);
                List<QFilter> qFilters = this.setQFilter(formId);
                showParameter.setCustomParam("filterParam", SerializationUtils.toJsonString(qFilters));
                showParameter.setCustomParam("LimitParam", "1");
            }

            String personId = this.getView().getPageCache().get("personId");
            if (HRStringUtils.isNotEmpty(personId)) {
                DynamicObject erFileDy = ErmanFileRepository.getPrimaryErmanFile(Long.parseLong(personId));
                this.setCustomParams(showParameter, erFileDy);
            }

            showParameter.setFormId(formId);
            showParameter.getCustomParams().put("cus_status", "cus_view");
            String ispreview = this.getPageCache().get("ispreview");
            if (HRStringUtils.isNotEmpty(ispreview)) {
                showParameter.setCustomParam("LimitParam", "1");
                showParameter.getCustomParams().put("ispreview", "1");
            }

            String cnfStr = this.getView().getPageCache().get("cnfjson");
            Map<String, Object> infoGroupConfig = (Map)SerializationUtils.fromJsonString(cnfStr, Map.class);
            List<Map<String, Object>> groups = (List)infoGroupConfig.get("mainentry");
            List<Map<String, Object>> params = (List)groups.stream().filter((group) -> {
                return ((String)group.get("targetkey")).equals(page);
            }).collect(Collectors.toList());
            if (params.size() > 0) {
                if (params.size() == 1 && ShowType.Floating == showType) {
                    showParameter.setCaption(((Map)params.get(0)).get("groupname").toString());
                }

                showParameter.setCustomParam("params", SerializationUtils.toJsonString(params.get(0)));
                showParameter.setCloseCallBack(new CloseCallBack(this, "hspm_infogroupedit_pop"));
            }

            showParameter.setHasRight(true);
            this.getView().showForm(showParameter);
        }
    }

    private boolean isOldHss(FormShowParameter formShowParameter) {
        return "hss_businessoffice".equals(formShowParameter.getParentFormId());
    }

    private List<QFilter> setQFilter(String formId) {
        ArrayList<QFilter> qFilters = new ArrayList();
        if (formId.contains("hspm_empposorgrel")) {
            QFilter primaryFilter = new QFilter("isprimary", "=", "1");
            QFilter statusFilter = new QFilter("businessstatus", "=", "1");
            QFilter versionFilter = new QFilter("iscurrentversion", "=", "1");
            qFilters.add(primaryFilter);
            qFilters.add(statusFilter);
            qFilters.add(versionFilter);
        } else if (formId.contains("hspm_pereduexp")) {
            qFilters.add(new QFilter("ishighestdegree", "=", "1"));
        } else if (formId.contains("hspm_preworkexp")) {
        }

        return qFilters;
    }

    private void setCustomParams(FormShowParameter showParameter, DynamicObject erFileDy) {
        showParameter.setCustomParam("person", erFileDy.getLong("person.id"));
        showParameter.setCustomParam("employee", erFileDy.getLong("employee.id"));
        showParameter.setCustomParam("depemp", erFileDy.getLong("depemp.id"));
        showParameter.setCustomParam("cmpemp", erFileDy.getLong("cmpemp.id"));
        showParameter.setCustomParam("empentrel", erFileDy.getLong("empentrel.id"));
        showParameter.setCustomParam("empposrel", erFileDy.getLong("empposrel.id"));
        showParameter.setCustomParam("name", erFileDy.getString("name"));
        showParameter.setCustomParam("erfileid", erFileDy.getLong("id"));
    }

    public void onProgress(ProgressEvent progressEvent) {
        String ispreview = this.getPageCache().get("ispreview");
        if (!HRStringUtils.isNotEmpty(ispreview)) {
            IFormView view = this.getView();
            ApprovalHelper.handleSubmitButtonVisible(view);
            this.refreshHeadPicture(view);
            this.initVisibleNotPassLabel();
        }
    }

    private void refreshHeadPicture(IFormView view) {
        boolean isEdit = this.isHeadNeedAuditOrIsEdit("isedit");
        if (isEdit) {
            view.setEnable(Boolean.TRUE, new String[]{"headsculpture"});
        } else {
            view.setEnable(Boolean.FALSE, new String[]{"headsculpture"});
        }

        String personIdStr = view.getPageCache().get("personId");
        DynamicObject bill = ApprovalHelper.getInProcessWorkFlowBill(Long.parseLong(personIdStr));
        if (bill != null) {
            DynamicObjectCollection entryentity = bill.getDynamicObjectCollection("entryentity");
            if (!CollectionUtils.isEmpty(entryentity)) {
                Iterator var6 = entryentity.iterator();

                while(var6.hasNext()) {
                    DynamicObject object = (DynamicObject)var6.next();
                    String targetkey = String.valueOf(object.get("firstgroupnum"));
                    if (targetkey.equals("0000")) {
                        String reason = HRStringUtils.isNotEmpty(object.getString("reason")) ? object.getString("reason") : ResManager.loadKDString("未填写不通过理由", "AbstractMobileFormDrawEdit_3", "hr-hspm-formplugin", new Object[0]);
                        if ("G".equals(bill.getString("billstatus")) && object.getBoolean("status")) {
                            this.setLabelText("notpassinfo", String.format(ResManager.loadKDString("您的头像已被驳回，不通过原因: %s", "MobileHomeTemplatePlugin_13", "hr-hspm-formplugin", new Object[0]), reason));
                            String closeHeadTipsPanel = view.getPageCache().get("closeHeadTipsPanel");
                            if (closeHeadTipsPanel == null) {
                                view.setVisible(true, new String[]{"headtipspanel"});
                                view.setVisible(true, new String[]{"notpassvector"});
                            }
                        }
                    }
                }

                if (!"G".equals(bill.getString("billstatus"))) {
                    view.setEnable(Boolean.FALSE, new String[]{"headsculpture"});
                }

            }
        }
    }
}
